home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: in2.uu.net!allegra!alice!ark
- From: ark@research.att.com (Andrew Koenig)
- Subject: Re: NEWBIE : Quicksort
- Message-ID: <Doxpq0.2t5@research.att.com>
- Organization: AT&T Research, Murray Hill NJ
- References: <4j4ruf$gf4@news1.h1.usa.pipeline.com> <Pine.SOL.3.91.960325221334.202B-100000@orion> <3159337A.2DB5@staff.ichange.com>
- Date: Wed, 27 Mar 1996 16:27:36 GMT
-
- In article <3159337A.2DB5@staff.ichange.com> Jesse Liberty <jl@staff.ichange.com> writes:
-
- > Sure, in my book Teach Yourself MORE C++ In 21 Days I show how to write a number of sorts, quicksort among them. Here's the
- > basic code.
-
- > template <class T>
- > void myQuickSort(T* Input, int left, int right)
- > {
- > if (right > left)
- > {
- > T target = Input[right-1];
- > int i = left-1;
- > int x = right-1;
- > for (;;)
- > {
- > while (*Input[++i] < *target)
- > ;
- > while (*Input[--x] > *target)
- > ;
- >
- > if (i >= x)
- > break;
- > Swap(Input[i], Input[x]);
- > }
-
- > Swap(Input[i], Input[right-1]);
- > myQuickSort(Input,left,i);
- > myQuickSort(Input,i+1,right);
- >
- > }
- > }
-
- > template <class T>
- > inline void Swap(T& i, T& j)
- > {
- > T temp;
- > temp = j;
- > j = i;
- > i = temp;
- > }
-
- I hope this isn't what's in the book.
-
- For one thing, this code doesn't sort the elements of an array in the ordinary
- sense. Rather, it sorts an array of pointers based on comparing the values
- to which the pointers point. That is, the comparisons
-
- *Input[++i] < *target
-
- and
-
- *Input[--x] > *target
-
- require that type T be a pointer type, or at least a type on which unary *
- is defined.
-
- There's nothing wrong with that, but it's a little surprising -- especially
- because that's *not* what the C or C++ library sort functions do.
-
- Moreover, the algorithm as shown has a shortcoming that is common to many
- implementations of quicksort: if you give it an array that is already
- sorted, its execution time is quadratic in the number of elements.
-
- I'm not aiming criticism at this book in particular, which I haven't read.
- What I'm trying to argue is that good algorithms are not easy to design,
- even when they appear simple. Libraries are there for a reason, and you
- should use them whenever it makes sense.
- --
- --Andrew Koenig
- ark@research.att.com
-